<?php

defined( 'IN_DICE' ) or die( 'Access Error!' );

class ModelTable extends base {
  
  function __construct() {
    parent::__construct();
  }
  
  /**
   * 根据tid来获取桌子信息
   *
   * @param int $tid
   * @return array
   */
  public function get( $tid ) {
    if( !$tid = uint( $tid ) ) {
      return array();
    }
    $sql = "SELECT * FROM $this->ttable WHERE tid='$tid' LIMIT 1";
    $aT = model::db()->get_one( $sql, MYSQL_NUM );
    return $aT;
  }
  
  
  /**
   * 根据模式与类型获得桌子列表
   * @param $ttype 桌子类型
   * @return array
   */
  public function getmulti($ttype) {
    $ttype = uint($ttype);
    $sql = "SELECT * FROM $this->ttable WHERE ttype='$ttype'";
    return model::db()->get_all( $sql );
  }
  
  /**
   * 快速加入房间
   * @param int $ttype 桌子类型
   * @return array
   */
  public function findTable( $ttype ) {
  }
  
  /**
   * 插入一条server表记录
   * @param array $aT server的相关信息
   * @return int
   */
  public function insert( $aT ) {
    if( empty( $aT ) || count( $aT ) < 4 || !$aT['tname'] || !$aT['svid'] ) {
      return 0;
    }
    $t = uint( $t );
    !$t && $t = 1;
    foreach ( $aT as $k => $v ) {
      $aT[$k] = model::db()->escape( $v );
    }
    $sql = "INSERT INTO $this->ttable SET tname='{$aT['tname']}',
            tname_th='{$aT['tname_th']}',tname_en='{$aT['tname_en']}',
            tseat='{$aT['tseat']}',ttype='{$aT['ttype']}',svid='{$aT['svid']}',
            tmax='{$aT['tmax']}',tminbet='{$aT['tminbet']}'";
    model::db()->exe( $sql );
    $id = model::db()->insertid();
    
    return (int)$id;
  }
  
  /**
   * 更新桌子信息
   * @param int $tid
   * @param array $aE
   * @return int
   */
  public function update( $tid, $aE ) {
    $tid = uint($tid);
    if( !$tid || !$aE ) {
      return 0;
    }
    $set = '';
    $aCan = array('tname', 'tname_th', 'tname_en', 'ttype', 'tseat', 'tminbet' );
    foreach ( $aE as $k => $v ) {
      $v = model::db()->escape( $v );
      if( in_array( $k, $aCan ) ) $set .= "$k='$v',";
    }
    isset($aE['svid']) && $aE['svid'] && $set .= "$svid='{$aE['svid']}',";
    if( !strlen( $set ) ) {
      return 0;
    }
    $set = substr( $set, 0, -1 );
    $sql = "UPDATE $this->ttable SET $set WHERE tid='$tid' LIMIT 1";
    model::db()->exe( $sql );
    $flag = model::db()->update_rows();
    return (int)$flag;
  }
  
  /**
   * 删除某个桌子
   *
   * @param int $tid
   * @return int
   */
  public function del( $tid ) {
    $tid = uint($tid);
    if( !$tid ) {
      return 0;
    }
    $sql = "DELETE FROM $this->ttable WHERE tid='$tid' LIMIT 1";
    model::db()->exe( $sql );
    $flag = model::db()->update_rows();
    return (int)$flag;
  }
}
